package com.yulebaby.callsenter.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.ShowReturnRecordAdapter;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.ui.base.BaseActivity;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.CommonUtil;
import com.yulebaby.callsenter.utils.ImageLoader;
import com.yulebaby.callsenter.utils.MediaPlayerUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;

/**
 * 上传文件activity
 *
 * @author 张博
 * @date 2017-1-12.
 */

public class UploadFileActivity extends BaseActivity implements MediaPlayerUtils.CompletionListener, View.OnClickListener {


    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;
    private static final int REQUEST_CODE_RECORD_SELECT = 3;


    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_save)
    TextView mTvSave;
    @BindView(R.id.rv_upload)
    RecyclerView mRvUpload;

    private ArrayList<CallLogBean> selectCallList;
    private ArrayList<ImageView> picCount;
    private ArrayList<String> picUrl;
    private ShowReturnRecordAdapter mCallLogAdapter;
    private int lastPosition = -1;
    private CallLogBean mClickCallLogBean;
    private MediaPlayerUtils mPlayerUtils;
    private Button mAddRecord;
    private LinearLayout mAddTrackPic;
    private int mWidth, mHeight, mMargin;
    private ArrayList pictureSelectList;
    private ImageView mDefaultView;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_uploadfile;
    }

    @Override
    protected void initView() {
        View header = LayoutInflater.from(this).inflate(R.layout.layout_upload_header, null);
        mAddTrackPic = (LinearLayout) header.findViewById(R.id.ll_addtrackpic);
        View footer = LayoutInflater.from(this).inflate(R.layout.layout_addbutton, null);
        mAddRecord = (Button) footer.findViewById(R.id.btn_common);
        mAddTrackPic.addView(getDefaultView()); //加载默认图片
        addSelectPicListener();
        mAddRecord.setOnClickListener(this);

        Intent intent = getIntent();
        ArrayList<String> picUrl = (ArrayList<String>) intent.getSerializableExtra(Constant.SELECED_PIC);
        ArrayList<CallLogBean> selectedList = (ArrayList<CallLogBean>) intent.getSerializableExtra(Constant.SELECED_RECORD);
        if (picUrl != null && picUrl.size() > 0) {
            pictureSelectList.addAll(picUrl);
            progressSelectPic(pictureSelectList);
        }

        if (selectedList != null && selectedList.size() > 0) {
            selectCallList.addAll(selectedList);
        }

        mCallLogAdapter.addHeaderView(header);
        mCallLogAdapter.addFooterView(footer);
        mRvUpload.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mClickCallLogBean = (CallLogBean) baseQuickAdapter.getItem(position);

                if (lastPosition != position) {
                    if (mPlayerUtils.isPlaying() && lastPosition != -1) {
                        mPlayerUtils.pause();
                        (((CallLogBean) baseQuickAdapter.getItem(lastPosition))).setPlayState(2);
                        mCallLogAdapter.notifyDataSetChanged();
                    }
                    lastPosition = position;
                }

                switch (view.getId()) {
                    case R.id.iv_play:
                        switch (mClickCallLogBean.getPlayState()) {
                            case 0:
                                ToastUtil.showToast("没有录音文件");
                                break;
                            case 1:
                                mPlayerUtils.pause();
                                mClickCallLogBean.setPlayState(2);
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                            case 2:
                                mClickCallLogBean.setPlayState(1);
                                String file_path = mClickCallLogBean.getFile_path();
                                if (file_path.startsWith("http://")) {
                                    mPlayerUtils.openAudio(Uri.parse(file_path));
                                } else {
                                    mPlayerUtils.openAudio(file_path);
                                }
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                        }
                        break;
                    case R.id.iv_state:
                        baseQuickAdapter.remove(position);
                        break;
                }
            }
        });

        mRvUpload.setAdapter(mCallLogAdapter);
    }

    /**
     * 加载默认图片
     */
    private void addSelectPicListener() {
        mDefaultView.setOnClickListener(v ->
                startActivityForResult(BGAPhotoPickerActivity.newIntent(this, null, 5 - picCount.size(), null, false), REQUEST_CODE_CHOOSE_PHOTO));

    }

    @NonNull
    private ImageView getDefaultView() {
        if (mDefaultView == null) {
            mDefaultView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mWidth, mHeight);
            params.leftMargin = 0;
            mDefaultView.setLayoutParams(params);
            ImageLoader.load(this, R.drawable.add_pictures, mDefaultView);
        }
        return mDefaultView;
    }

    @Override
    protected void initData() {

        selectCallList = new ArrayList<>();
        pictureSelectList = new ArrayList<>();
        picCount = new ArrayList<>();
        picUrl = new ArrayList<>();


        mWidth = CommonUtil.getDimens(R.dimen.space_106);
        mHeight = CommonUtil.getDimens(R.dimen.space_106);
        mMargin = CommonUtil.getDimens(R.dimen.space_7);

        mRvUpload.setHasFixedSize(true);
        mRvUpload.setLayoutManager(new YuLeBaByLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mCallLogAdapter = new ShowReturnRecordAdapter(selectCallList);
        mPlayerUtils = MediaPlayerUtils.getInstances();
        mPlayerUtils.setOnCompletionListener(this);
    }


    @Override
    public void Completion() {
        mClickCallLogBean.setPlayState(2);
        mCallLogAdapter.notifyDataSetChanged();
    }


    @OnClick({R.id.iv_back, R.id.tv_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                Intent intent = new Intent();
                intent.putExtra(Constant.SELECED_PIC, picUrl);
                intent.putExtra(Constant.SELECED_RECORD, selectCallList);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.btn_common:
                Intent recordIntent = new Intent(UploadFileActivity.this, ShowReturnRecordActivity.class);
                ArrayList<Long> list = new ArrayList<>();
                for (CallLogBean callLogBean : selectCallList) {
                    list.add(callLogBean.getCall_time());
                }
                recordIntent.putExtra(Constant.CALL_TIME, list);
                startActivityForResult(recordIntent, REQUEST_CODE_RECORD_SELECT);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            progressSelectPic(BGAPhotoPickerActivity.getSelectedImages(data));
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            progressSelectPic(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_RECORD_SELECT) {
            progressSelectRecord((ArrayList<CallLogBean>) data.getSerializableExtra(Constant.SELECED_RECORD));
        }
    }

    /**
     * 录音
     *
     * @param list
     */
    private void progressSelectRecord(ArrayList<CallLogBean> list) {
        selectCallList.addAll(list);
        mCallLogAdapter.notifyDataSetChanged();
    }

    /**
     * 图片
     *
     * @param selectedImages
     */
    private void progressSelectPic(ArrayList<String> selectedImages) {
        if (mDefaultView != null) {
            mAddTrackPic.removeView(mDefaultView);
        }
        for (int i = 0; i < selectedImages.size(); i++) {
            ImageView imageView = new ImageView(UploadFileActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mWidth, mHeight);
            params.leftMargin = picCount.size() == 0 ? 0 : mMargin;
            imageView.setLayoutParams(params);
            ImageLoader.load(UploadFileActivity.this, selectedImages.get(i), imageView);
            mAddTrackPic.addView(imageView);
            picUrl.add(selectedImages.get(i));
            picCount.add(imageView);
        }
        if (picCount.size() < 5) {
            ImageView defaultView = getDefaultView();
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) defaultView.getLayoutParams();
            params.leftMargin = picCount.size() == 0 ? 0 : mMargin;
            mAddTrackPic.addView(defaultView);
        }
    }
}
